﻿using System;
using System.Collections.Generic;
using System.Linq;
using ConfOrm;
using ConfOrm.NH;
using NHDay_Linq.Domain;
using NHDay_Linq.UserTypes;

namespace NHDay_Linq.ConfORM
{
	public class DomainMapping : IDomainMapping
	{
		#region Implementation of IModuleMapping

		public void DomainDefinition(ObjectRelationalMapper orm)
		{
			// define the mapping for all the types
			orm.Complex<Item>();

			// defines the whole hierarchy coming up from person
			orm.TablePerClassHierarchy<Person>();

			// entrities that should not be mapped (they are implemented with a WellKnownType)
			Type[] exclusionList = new[] {typeof(Item), typeof(Items)};

			// defines all the other entities
			IEnumerable<Type> baseEntities = GetEntities().Where(t => !typeof(Person).IsAssignableFrom(t) &&
				!exclusionList.Contains(t));
			
			orm.TablePerClass(baseEntities);
		}

		public void RegisterPatterns(Mapper mapper, IDomainInspector domainInspector)
		{
		}

		public void Customize(Mapper mapper)
		{
			CustomizeRelations(mapper);
			CustomizeTables(mapper);
			CustomizeColumns(mapper);
		}

		public IEnumerable<Type> GetEntities()
		{
			return typeof(Person).Assembly.GetTypes().Where(t => t.Namespace == typeof(Person).Namespace);
		}

		#endregion

		private static void CustomizeRelations(Mapper mapper)
		{
			
		}

		private static void CustomizeColumns(Mapper mapper)
		{
			
		}

		private static void CustomizeTables(Mapper mapper)
		{
			// add a Custom UserType
			mapper.TypeDef<Item, ItemsUserType>();
		}
	}
}
